<template>
  <main-content title="配置礼品包"  back :back-func="true" @back="leaveConfirm" >
    <el-form ref="giftPackFormRef" :label-width="130" :model="form">
      <goods-center-notice>
        <template #content>
          礼品包商品领取后不支持售后退款，请在商品使用说明里面备注明确。
        </template>
      </goods-center-notice>
      <goods-center-section-title content="礼包信息"></goods-center-section-title>
      <gift-pack-name v-model:model-value="form.name"></gift-pack-name>
      <gift-pack-img v-model:model-value="form.thumbnailUrl"></gift-pack-img>
      <gift-pack-num v-model:model-value="form.packNum"></gift-pack-num>
      <gift-pack-add-or-deduction-stock-count
          show-symbol="+"
          v-model:model-value="form.addOrDeductionStockCount">
      </gift-pack-add-or-deduction-stock-count>


      <goods-center-notice>
        <template #content>
          礼品包类型为全选，礼品包内各商品规格的库存必须≥礼品包库存，若商品规格库存＜礼品包库存，则不允许创建。
        </template>
      </goods-center-notice>
      <goods-center-section-title content="规格与库存"></goods-center-section-title>
      <prize-list
          v-model:model-value="currentPrizeTab"
          :list="prizeList"
          @tab-change="handleChangePrize"
          @click-add="handleAddPrize"
          @click-delete="handleDeletePrize"
      >
      </prize-list>

      <template v-if="currentPrizeTab > -1">
        <!--        商品名称-->
        <goods-name readonly :model-value="currentGoodsEntity.name">
          <template #append>
            <el-button type="primary" link @click="showEditGoods(currentGoodsEntity)">查看商品信息</el-button>
          </template>
        </goods-name>

        <!--        商品分类-->
        <goods-type readonly :model-value="currentGoodsEntity.type"></goods-type>

        <!--        所属商家-->
        <goods-store-name :model-value="currentGoodsEntity.storeName"></goods-store-name>

        <!--        商品规格-->
        <product-selector
            v-model:model-value="selectedProductId"
            :gift-pack-form="form"
            :options="currentStoreProducts"
            @change="handleGoodsProductChange">
          <template #append>
            <el-button
                type="primary"
                link
                @click="showEditProduct(currentGoodsEntity, currentProduct)">
              查看规格信息
            </el-button>
          </template>
        </product-selector>

        <!--        商家剩余库存-->
        <product-before-stock :value="currentProduct.beforeStock"></product-before-stock>

        <!--        不是全部类型的礼品包 调整具体奖品库存-->
        <product-stock-add-or-decount
            v-if="form.packNum !== -1"
            v-model:model-value="prizeAddOrDeductionStockCount">
        </product-stock-add-or-decount>

        <el-form-item prop="prize" :rules="prizeRules"></el-form-item>
      </template>

      <goods-center-section-title content="使用说明"></goods-center-section-title>
      <gift-pack-description v-model:model-value="form.description" :init-value="initDesValue"></gift-pack-description>

      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
<!--        <el-button @click="test">打印form</el-button>-->
      </el-form-item>
    </el-form>
  </main-content>

  <!--    新增商品，选择商品新增-->
  <select-goods
      v-model:show="isShowSelectGoods"
      table-url="/merchant/member/goods/pageStoreProduct"
      :table-param="selectForm"
      @select="handleSelect">
    <template #search>
      <search-bar inline>
        <template #normal>
          <el-form-item label="商品名称">
            <el-input v-model="selectForm.name" placeholder="请输入商品名称" clearable></el-input>
          </el-form-item>
          <goods-supplier-filter
              url="merchant/member/goods/getStore"
              @change="({selected}) => selectForm.storeIds = [selected]">
          </goods-supplier-filter>
        </template>
      </search-bar>
    </template>
  </select-goods>

  <!--    编辑商品-->
  <edit-goods
      v-model:show="isShowEditGoods"
      :row-data="currentEditingRow"
      @click-submit="handleEditGoodsDone"
  ></edit-goods>

  <!--  编辑规格-->
  <edit-gift-pack-product
      v-model:show="isShowEditProduct"
      :form-props="['name', 'thumbnailUrl']"
      :gift-pack-form="form"
      :product-row-data="currentProductRowForEditProduct"
      :row-data="currentGoodsRowForEditProduct"
      @click-submit="handleEditProductDone">
  </edit-gift-pack-product>
</template>

<script lang="ts" setup>
import {ComputedRef, Ref, WritableComputedRef} from "vue"
import {IGoodsPageRow, IStoreGoodsPageRow, IStoreProductRow} from "@/api/modules/pointsMall";

import {useLeaveConfirm} from "@/components/goodsCenter/compositions/useLeaveConfirm";

// 礼品包配置Form
import GiftPackName from "@/components/goodsCenter/addGiftPackFormItem/GiftPackName.vue"
import GiftPackImg from "@/components/goodsCenter/addGiftPackFormItem/GiftPackImg.vue"
import GiftPackNum from "@/components/goodsCenter/addGiftPackFormItem/GiftPackNum.vue"
import GiftPackAddOrDeductionStockCount from "@/components/goodsCenter/addGiftPackFormItem/GiftPackAddOrDeductionStockCount.vue"
import PrizeList from "@/components/goodsCenter/addGiftPackFormItem/PrizeList.vue"
import GiftPackDescription from "@/components/goodsCenter/addGiftPackFormItem/GiftPackDescription.vue"

// 奖品
import GoodsName from "@/components/goodsCenter/addGoodsFormItem/GoodsName.vue"
import GoodsType from "@/components/goodsCenter/addGoodsFormItem/GoodsType.vue"
import GoodsStoreName from "@/components/goodsCenter/addGoodsFormItem/GoodsStoreName.vue"
import ProductSelector from "@/components/goodsCenter/addGoodsFormItem/ProductSelector.vue"
import ProductBeforeStock from "@/components/goodsCenter/addProductFormItem/ProductBeforeStock.vue"

// 选择商品
import SelectGoods from "@/components/goodsCenter/SelectGoods.vue"
import {useGoodsSelect} from "@/components/goodsCenter/compositions/useGoodsSelect";
import {IAddGiftPackData, IGiftPackGoodProduct, IGiftPackGoodsEntity} from "@/api/modules/vipCenter";
import {useEditGoods} from "@/components/goodsCenter/compositions/useEditGoods";

// 编辑商品
import EditGoods from "@/components/goodsCenter/EditGoods.vue"

// 编辑规格
import EditGiftPackProduct from "@/components/goodsCenter/EditGiftPackProduct.vue"
import {useEditProduct} from "@/components/goodsCenter/compositions/useEditProduct";
import {addGiftPack} from "@/api/vipCenter";
import GoodsCenterSectionTitle from "@/components/goodsCenter/common/GoodsCenterSectionTitle.vue";

const router = useRouter()

const giftPackFormRef = ref()
const form = reactive<IAddGiftPackData>({
  name: '', // 礼品包名称
  thumbnailUrl: '', // 礼品包图片
  packNum: -1, // 礼品包类型
  type: 'pack',
  addOrDeductionStockCount: 1,
  goodsEntities: [],
  products: [] as Omit<IAddGiftPackData, 'goodsEntities'>[]
})
const initDesValue=ref('')

const prizeRules = [{
  validator(rule: any, value: any, callback: any) {
    if (form.packNum !== -1) {
      const productStockSum = form.goodsEntities.reduce((total, current) => {
        return total + (current.products?.[0]?.addOrDeductionStockCount ?? 0)
      }, 0)

      if (productStockSum < form.addOrDeductionStockCount) {
        callback('当前礼品包类型不为全部，各商品规格库存总和必须大于等于礼品包库存。请检查规格库存配置，或者配置礼品包类型为全部')
        return
      }
    }

    callback()
  }
}]

// 奖品tab
// [商家] 商品goodsEntities
const prizeList = ref<IStoreGoodsPageRow[]>([])
// 奖品TabIndex
const currentPrizeTab:Ref<string> = ref('-1')
// 当前奖品tab下的商家商品的规格可选列表
const currentStoreProducts:ComputedRef<IStoreProductRow[]> = computed(() => {
  return prizeList.value[Number(currentPrizeTab.value)]?.products ?? []
})

// const currentGoodsEntity:Ref<IGoodsPageRow> = ref({} as any)
// 当前form表单的goodsEntity
const currentGoodsEntity:ComputedRef<IGiftPackGoodsEntity> = computed(() => {
  return form.goodsEntities[Number(currentPrizeTab.value)] ?? {}
})
// 当前form表单的product 单选
const currentProduct = computed(() => {
  return currentGoodsEntity.value?.products?.[0] ?? {}
})

const handleAddPrize = () => {
  showGoodSelect()
}
const handleDeletePrize = (prize: IStoreGoodsPageRow, index: number, list: IStoreGoodsPageRow[]) => {
  currentPrizeTab.value = Number(currentPrizeTab.value) - 1 + ''
  prizeList.value.splice(index, 1)
  form.goodsEntities.splice(index, 1)
}
const handleChangePrize = (index: string) => {
  selectedProductId.value = currentGoodsEntity.value.products?.[0]?.storeProductId ?? null
}

// 奖品tab - 新增商品 选择商品
const { isShowSelectGoods, showGoodSelect, selectForm } = useGoodsSelect()

const handleSelect = (rowData: IStoreGoodsPageRow) => {
  // console.log('handle select rowData: ', rowData)
  isShowSelectGoods.value = false
  const nextPrizeTab = Number(currentPrizeTab.value) + 1

  // 存储storeRowData
  prizeList.value.push(JSON.parse(JSON.stringify(rowData)))

  // form --> goodsEntity
  form.goodsEntities.push(makeGoodsEntity(rowData))

  // form --> product
  if (rowData.products?.[0]) {
    const storeProduct = rowData.products[0]
    form.goodsEntities[nextPrizeTab].products!.push(makeGoodsProduct(storeProduct, rowData))
    selectedProductId.value = storeProduct.id
  }

  // 显示当前tab
  // currentGoodsEntity.value = form.goodsEntities[nextPrizeTab]
  currentPrizeTab.value = nextPrizeTab + ''
}

// 为form创建一个goodsEntity
const makeGoodsEntity: (rowData: IStoreGoodsPageRow) => IGiftPackGoodsEntity = (rowData) => {
  const _goodsEntity = {} as any
  _goodsEntity.storeGoodsId = rowData.id
  _goodsEntity.name = rowData.name
  _goodsEntity.thumbnailUrl = rowData.thumbnailUrl
  _goodsEntity.detailText = rowData.detailText
  _goodsEntity.description = rowData.description
  _goodsEntity.addOrDeductionStockCount = 1
  _goodsEntity.products = []
  _goodsEntity.type = rowData.type
  _goodsEntity.storeId = rowData.storeId
  _goodsEntity.storeName = rowData.storeName

  return _goodsEntity
}

// 为form goodsEntity创建一个product
const makeGoodsProduct: (productRow: IStoreProductRow, goodsRow: IStoreGoodsPageRow) => IGiftPackGoodProduct = (productRow, goodsRow) => {
  const _product = {} as any
  _product.storeProductId = productRow.id
  _product.storeGoodsId = goodsRow.id
  _product.name = productRow.name
  _product.thumbnailUrl = productRow.thumbnailUrl
  _product.addOrDeductionStockCount = 1
  _product.beforeStock = productRow.beforeStock

  return _product
}

// 奖品tab - 选择规格
const selectedProductId:Ref<number | null> = ref(null)
const handleGoodsProductChange = (storeProductId: number) => {
  const targetProduct = currentStoreProducts.value.find(item => item.id === storeProductId)

  const numberTabIndex = Number(currentPrizeTab.value)
  // 单一规格
  if (form.goodsEntities[numberTabIndex]) {
    if (form.goodsEntities[numberTabIndex].products) {
      form.goodsEntities[numberTabIndex].products[0] = makeGoodsProduct(targetProduct!, prizeList.value[numberTabIndex])
    }
  }
}

// 奖品tab - 不是全部类型的礼品包调整具体奖品库存
const prizeAddOrDeductionStockCount:WritableComputedRef<number> = computed({
  get() {
    return currentGoodsEntity.value?.addOrDeductionStockCount
  },
  set(newValue) {
    form.goodsEntities[Number(currentPrizeTab.value)].addOrDeductionStockCount = newValue
    form.goodsEntities[Number(currentPrizeTab.value)].products[0].addOrDeductionStockCount = newValue
  },
})

// 编辑商品
const {isShowEditGoods, showEditGoods, currentEditingRow} = useEditGoods()
const handleEditGoodsDone = (editForm:any) => {
  isShowEditGoods.value = false
  const targetIndex = form.goodsEntities.findIndex(item => item.storeGoodsId === editForm.storeGoodsId)
  if (targetIndex > -1) {
    Object.keys(editForm).forEach(key => {
      form.goodsEntities[targetIndex][key] = editForm[key]
    })
  }
}

// 编辑规格
const {
  isShowEditProduct,
  showEditProduct,
  currentGoodsRowForEditProduct,
  currentProductRowForEditProduct
} = useEditProduct()
const handleEditProductDone = (editForm:any) => {
  isShowEditProduct.value = false
  const targetIndex = form.goodsEntities.findIndex(item => item.products![0].storeProductId === editForm.storeProductId)

  if (targetIndex > -1) {
    form.goodsEntities[targetIndex].products = [{...editForm}]
  }
}

const formatData = (form: IAddGiftPackData) => {
  const _form = JSON.parse(JSON.stringify(form)) as IAddGiftPackData

  // form.products
  const giftPackProduct = {} as Omit<IAddGiftPackData, 'goodsEntities' | 'products'>
  Object.keys(form)
    .filter(key => key !== 'goodsEntities' && key !== 'products')
    .forEach(key => giftPackProduct[key] = _form[key])
  _form.products = [giftPackProduct]

  if (form.packNum === -1) {
    _form.goodsEntities.forEach(item => {
      item.addOrDeductionStockCount = form.addOrDeductionStockCount
      item.products![0].addOrDeductionStockCount = form.addOrDeductionStockCount
    })
  }

  return _form
}

const submit = async () => {
  giftPackFormRef.value?.validate(async (valid: boolean, fields:any) => {
    if (valid) {
      const _form = formatData(form)
      const rs = await addGiftPack(_form)
      if (rs.code === 200) {
        ElMessage.success('创建成功')
        router.back()
      }
    }
  })
}

const test = () => {
  giftPackFormRef.value?.validate(async (valid: boolean, fields:any) => {
    if (valid) {
      const _form = formatData(form)
      console.log(_form)
    }
  })

  const _form = formatData(form)
  console.log(_form)
}

const {leaveConfirm} = useLeaveConfirm()
</script>

<style scoped lang="scss">

</style>
